<?php
class facebook_app{
  function handleError(){
    global $core;
    $core->addAlert('$$facebook_connectError$$: '.$_GET["error_description"]);
    header("location:/");
    exit;
  }
  function getAuthURL($client,$returnURL,$scope=array()){
  	$url = 'https://www.facebook.com/dialog/oauth/?client_id='.$client
  			.'&redirect_uri='.urlencode($returnURL)
  			.'&scope='.implode(",",$scope);
	return $url;
  }
  function submitCode($code){
    global $config, $core, $user,$document;
    $url="https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URI&client_secret=YOUR_APP_SECRET&code=CODE_GENERATED_BY_FACEBOOK";
    $p=array(
      "YOUR_APP_ID"=>$config->defaults["facebook"]->app_id,
      "YOUR_REDIRECT_URI"=>urlencode($config->paths["url"]."user/loginwithfacebook"),
      "YOUR_APP_SECRET"=>$config->defaults["facebook"]->app_secret,
      "CODE_GENERATED_BY_FACEBOOK"=>urlencode($code)
      );
    $url=str_replace(array_keys($p),$p,$url);
    //echo $url;
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_USERAGENT, 'facebook-php-3.1');

    $respuesta=curl_exec($ch);
    curl_close($ch);

    //echo $respuesta;
    $respuestap=explode("&",$respuesta);
    $code=array();
    foreach($respuestap as $r){
	$r=explode("=",$r);
	$code[$r[0]]=$r[1];
    }
    if($code["access_token"]){
    	return $user->loginFacebook($code);
	}
	else {
		return false;
	}
  }
	function parse_signed_request($signed_request, $secret) {
	  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
	
	  // decode the data
	  $sig = $this->base64_url_decode(strtr($encoded_sig, '-_', '+/'));
	  $data = json_decode($this->base64_url_decode(strtr($payload, '-_', '+/')), true);
	
	  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
	    //error_log('Unknown algorithm. Expected HMAC-SHA256');
	    return null;
	  }
	
	  // check sig
	  $expected_sig = hash_hmac('sha256', ($payload), $secret, $raw = true);
	  if ($sig !== $expected_sig) {
	    //error_log('Bad Signed JSON signature!');
	    return null;
	  }
	
	  return $data;
	}
	
	function base64_url_decode($input) {
	  return base64_decode(strtr($input, '-_', '+/'));
	}
	function getData($token){
		if(!$this->userdata){
			$url="https://graph.facebook.com/me?access_token=".$token;
			$this->userdata=$this->request($url);
			}
		return $this->userdata;
	}
	
  function request($url,$POST=false,$custom=false){
  	if(is_array($POST)){
		$po=array();
		foreach(array_keys($POST) as $k){
			$po[]=$k."=".$POST[$k];
		}}
		
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1) ;
    curl_setopt($ch, CURLOPT_USERAGENT, 'paypal-pay-php-3.1');
	
  	if(is_array($POST)){
		if($custom){
		    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $custom) ;
			}
		else{
		    curl_setopt($ch, CURLOPT_POST, 1);
			}
    curl_setopt($ch, CURLOPT_POSTFIELDS, implode("&",$po));
	}
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);


    $respuesta=curl_exec($ch);
	//print_r($respuesta);
	$respuesta=$this->parseRespuesta($respuesta);
	return $respuesta;
  }
  function parseRespuesta($respuesta){
  	$respuesta=json_decode($respuesta);
	return $respuesta;
  }
  function getLikes($token,$pageid=false){
  	$url="https://graph.facebook.com/me/likes".($pageid?"/$pageid":"")."?access_token=".$token;
	$likes=$this->request($url);
	return $likes->data;
  }
  function createEventonPage($token,$page_id,$titulo,$fecha1,$fecha2,$descripcion,$data=array()){
  	$url="https://graph.facebook.com/$page_id/events?access_token=".$token;
	$POST=array(
		"access_token"=>$token,
		"name"=>$titulo,
		"start_time"=>date("c",$fecha1),
		"end_time"=>date("c",$fecha2),
		"description"=>$descripcion,
		"location"=>$data["location"],
		"location_id"=>$data["location_id"]
		);
	$respuesta=$this->request($url,$POST);
	return $respuesta;
  }
  function updateEventonPage($page,$event,$user,$datos,$token){
  	$url="https://graph.facebook.com/".$user."/accounts?access_token=".$token;
	$accounts=$this->request($url);
	
	foreach($accounts->data as $a){
		if ($a->id==$page){
			$token=$a->access_token;
			break;
		}
	}
	
	
  	$url="https://graph.facebook.com/$event/?access_token=".$token;
	$datos["access_token"]=$token;
	$respuesta=$this->request($url,$datos);
	return($respuesta);
  }
  function deleteEvent($id,$token,$user,$page){
  	$url="https://graph.facebook.com/".$user."/accounts?access_token=".$token;
	$accounts=$this->request($url);
  	
	foreach($accounts->data as $a){
		if ($a->id==$page){
			$token=$a->access_token;
			break;
		}
	}
	
  	$url="https://graph.facebook.com/$id/?access_token=".$token;
	$data=array(
		"access_token"=>$token
		);
	return $this->request($url,$data,"DELETE");
  }
  function asistirEvento($id,$token){
  	$url="https://graph.facebook.com/".$id."/attending?access_token=".$token;
	$POST=array(
		"access_token"=>$token
		);
	$respuesta=$this->request($url,$POST);
	return $respuesta;
  }
  function noAsistirEvento(){
  	$url="https://graph.facebook.com/".$id."/attending?declined=".$token;
	$POST=array(
		"access_token"=>$token
		);
	$respuesta=$this->request($url,$POST);
	return $respuesta;
  	
  }
  function publish($data,$token){
  	$url="https://graph.facebook.com/me/feed";
  	$data["access_token"]=$token;
	$respuesta=$this->request($url,$data);
  	return $respuesta;
  }
}
